package com.gbt32960;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * GBT32960Tool: 32960协议解析工具（由32960decode.min.js翻译而来，分阶段实现）
 */
public class GBT32950Decoder
{
    // 字典映射（部分实现，后续补全）
    public static final Map<String, String> DATA_TYPE = new HashMap<>();
    public static final Map<String, String> DATA_TYPE_ACK = new HashMap<>();
    public static final Map<String, String> ENCRYPT_TYPE = new HashMap<>();
    public static final Map<String, String> REALTIME_DATA_TYPE = new HashMap<>();
    public static final Map<String, String> CAR_STATUS = new HashMap<>();
    public static final Map<String, String> CHARGE_STATUS = new HashMap<>();
    public static final Map<String, String> RUN_MODE = new HashMap<>();
    public static final Map<String, String> DCDC_STATUS = new HashMap<>();
    public static final Map<String, String> MOTOR_STATUS = new HashMap<>();
    public static final Map<String, String> ENGINE_STATUS = new HashMap<>();
    public static final Map<String, String> ALARM_LEVEL = new HashMap<>();
    public static final Map<String, String> OTA_TYPE = new HashMap<>();
    public static final Map<String, String> OTA_STATUS = new HashMap<>();
    public static final Map<String, String> OTA_RESULT = new HashMap<>();

    static {
        // 仅部分映射，后续可补全
        DATA_TYPE.put("01", "车辆登录");
        DATA_TYPE.put("02", "实时信息上报");
        DATA_TYPE.put("03", "补发信息上报");
        DATA_TYPE.put("04", "车辆登出");
        DATA_TYPE.put("07", "心跳");
        DATA_TYPE.put("08", "终端校时");
        DATA_TYPE.put("80", "查询命令");
        DATA_TYPE.put("81", "设置命令");
        DATA_TYPE.put("82", "车载终端控制命令");
        DATA_TYPE.put("C1", "升级结果状态上报");
        DATA_TYPE.put("C2", "ECU升级结果");
        DATA_TYPE.put("C3", "短信唤醒登出");
        DATA_TYPE.put("C4", "DTC数据上报");
        DATA_TYPE.put("C5", "T-BOX注册");
        DATA_TYPE.put("C6", "唯一识别码");
        DATA_TYPE.put("C7", "ECU信息查询");
        DATA_TYPE.put("C8", "唤醒方式");
        DATA_TYPE.put("C9", "自定义报警");
        DATA_TYPE.put("CA", "升级进度上报");
        DATA_TYPE.put("CD", "通用报警");

        // DATA_TYPE_ACK（修正为与32960decode.min.js一致）
        DATA_TYPE_ACK.put("01", "成功");
        DATA_TYPE_ACK.put("02", "错误");
        DATA_TYPE_ACK.put("03", "VIN重复");
        DATA_TYPE_ACK.put("04", "未登录");
        DATA_TYPE_ACK.put("FE", "命令包");
        DATA_TYPE_ACK.put("0A", "供应商为空或者供应商编码不存在");
        DATA_TYPE_ACK.put("0B", "T-box 类型为空或者 T-box 类型不存在");
        DATA_TYPE_ACK.put("0C", "T-box 编号为空或格式错误");
        DATA_TYPE_ACK.put("0D", "ICCID 为空或格式错误");
        DATA_TYPE_ACK.put("0E", "IMEI为空或格式错误");
        DATA_TYPE_ACK.put("0F", "T-box 已注册使用");
        DATA_TYPE_ACK.put("10", "tuid 编号为空或格式错误");

        // ENCRYPT_TYPE
        ENCRYPT_TYPE.put("01", "不加密");
        ENCRYPT_TYPE.put("02", "RSA加密");
        ENCRYPT_TYPE.put("03", "AES128加密");
        ENCRYPT_TYPE.put("FE", "异常");
        ENCRYPT_TYPE.put("FF", "无效");

        // REALTIME_DATA_TYPE
        REALTIME_DATA_TYPE.put("01", "整车数据");
        REALTIME_DATA_TYPE.put("02", "驱动电机数据");
        REALTIME_DATA_TYPE.put("03", "燃料电池数据");
        REALTIME_DATA_TYPE.put("04", "发动机数据");
        REALTIME_DATA_TYPE.put("05", "车辆位置数据");
        REALTIME_DATA_TYPE.put("06", "DTC数据");
        REALTIME_DATA_TYPE.put("07", "报警数据");
        REALTIME_DATA_TYPE.put("08", "可充电储能装置电压数据");
        REALTIME_DATA_TYPE.put("09", "可充电储能装置温度数据");
        REALTIME_DATA_TYPE.put("96", "新能源车况数据");
        REALTIME_DATA_TYPE.put("89", "报警等级上报");

        // CAR_STATUS
        CAR_STATUS.put("01", "车辆启动状态");
        CAR_STATUS.put("02", "熄火");
        CAR_STATUS.put("03", "其他");
        CAR_STATUS.put("FE", "异常");
        CAR_STATUS.put("FF", "无效");

        // CHARGE_STATUS
        CHARGE_STATUS.put("01", "停车充电");
        CHARGE_STATUS.put("02", "行驶充电");
        CHARGE_STATUS.put("03", "未充电");
        CHARGE_STATUS.put("04", "充电完成");
        CHARGE_STATUS.put("FE", "异常");
        CHARGE_STATUS.put("FF", "无效");

        // RUN_MODE
        RUN_MODE.put("01", "纯电");
        RUN_MODE.put("02", "混动");
        RUN_MODE.put("03", "燃油");
        RUN_MODE.put("FE", "异常");
        RUN_MODE.put("FF", "无效");

        // DCDC_STATUS
        DCDC_STATUS.put("01", "工作");
        DCDC_STATUS.put("02", "断开");
        DCDC_STATUS.put("FE", "异常");
        DCDC_STATUS.put("FF", "无效");

        // MOTOR_STATUS
        MOTOR_STATUS.put("01", "耗电");
        MOTOR_STATUS.put("02", "发电");
        MOTOR_STATUS.put("03", "关闭");
        MOTOR_STATUS.put("04", "准备");
        MOTOR_STATUS.put("FE", "异常");
        MOTOR_STATUS.put("FF", "无效");

        // ENGINE_STATUS
        ENGINE_STATUS.put("01", "启动");
        ENGINE_STATUS.put("02", "关闭");
        ENGINE_STATUS.put("FE", "异常");
        ENGINE_STATUS.put("FF", "无效");

        // ALARM_LEVEL
        ALARM_LEVEL.put("00", "无故障");
        ALARM_LEVEL.put("01", "一级");
        ALARM_LEVEL.put("02", "二级");
        ALARM_LEVEL.put("03", "三级");
        ALARM_LEVEL.put("FE", "异常");
        ALARM_LEVEL.put("FF", "无效");

        // OTA_TYPE
        OTA_TYPE.put("01", "启动升级");
        OTA_TYPE.put("02", "升级结果");

        // OTA_STATUS
        OTA_STATUS.put("00", "成功");
        OTA_STATUS.put("01", "失败");

        // OTA_RESULT
        OTA_RESULT.put("00", "成功");
        OTA_RESULT.put("01", "失败");
    }

    // 工具方法示例：将十六进制字符串转为int
    public static int hex2int(String hex) {
        return Integer.parseInt(hex, 16);
    }

    public static long hex2long(String hex) {
        return Long.parseLong(hex, 16);
    }

    // 示例：格式化时间
    public static String getTime(String y, String m, String d, String h, String min, String s) {
        return String.format("%d-%02d-%02d %02d:%02d:%02d", hex2int(y), hex2int(m), hex2int(d), hex2int(h),
                hex2int(min), hex2int(s));
    }

    // 解析入口方法，仿照JS decode函数，返回Map结构
    public static Map<String, Object> decode(String hexStr) {
        Map<String, Object> result = new HashMap<>();
        String formatted = formatHex(hexStr).toUpperCase();
        if (formatted.isEmpty())
            return result;
        // 校验格式
        if (!formatted.matches("^([0-9A-F]{1,2}\\s)*([0-9A-F]{1,2})?$"))
            return result;
        String[] arr = formatted.split(" ");
        if (!(arr[0].equals("23") && arr[1].equals("23") || arr[0].equals("24") && arr[1].equals("24")))
            return result;
        // BCC校验
        int bcc = 0;
        for (int i = 2; i < arr.length - 1; i++) {
            if (arr[i].isEmpty())
                continue;
            try {
                // 修改为与JS一致的十六进制处理方式
                bcc ^= Integer.parseInt(arr[i], 16);
            } catch (Exception e) {
                continue;
            }
        }
        String bccStr = Integer.toHexString(bcc).toUpperCase();
        if (bccStr.length() == 1)
            bccStr = "0" + bccStr;
        // if (!arr[arr.length - 1].equals(bccStr)) return result;
        // 起始符
        result.put("起始符", (char) hex2int(arr[0]) + String.valueOf((char) hex2int(arr[1])));
        // 起始符
        String startChar = (char) hex2int(arr[0]) + String.valueOf((char) hex2int(arr[1]));
        // 命令单元
        Map<String, String> cmd = new HashMap<>();
        cmd.put("命令标识", getDataType(arr[2]));
        cmd.put("应答标志", getDataTypeAck(arr[3]));
        result.put("命令单元", cmd);
        // 唯一识别码
        result.put("唯一识别码", getUnique(arr));
        // 加密方式
        result.put("数据单元加密方式", getEncryptType(arr[21]));
        // 数据单元长度
        int dataLen = hex2int(arr[22] + arr[23]);
        result.put("数据单元长度", dataLen);
        // 数据单元内容
        // 数据单元内容（按JS原意应为字符串数组，且去除空字符串）
        List<String> dataUnitList = new ArrayList<>();
        for (int i = 24; i < arr.length - 1; i++) {
            dataUnitList.add(arr[i]);
        }
        String[] dataUnitArr = dataUnitList.toArray(new String[0]);
        result.put("数据单元内容", dataUnitArr);
        // 长度校验
        // if (dataUnitArr.length != dataLen-24) return result;
        // TODO: 可根据命令标识进一步解析数据单元内容
        String cmdType = cmd.get("命令标识");
        if (cmdType != null && !cmdType.equals("未知")) {
            String[] dataUnit = (String[]) result.get("数据单元内容");
            result.put("数据单元内容", parseDataUnit(cmdType, dataUnit, startChar));
        }
        return result;
    }

    // 辅助方法：格式化16进制字符串（去空格，每两位加空格）
    public static String formatHex(String s) {
        s = s.replaceAll(" ([0-9A-Fa-f]) ", " 0$1 ");
        s = s.replaceAll("\\s", "");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            sb.append(s.charAt(i));
            if (i % 2 == 1 && i != s.length() - 1)
                sb.append(' ');
        }
        return sb.toString();
    }

    // 获取命令标识
    public static String getDataType(String code) {
        return DATA_TYPE.getOrDefault(code, "未知");
    }

    // 获取应答标志
    public static String getDataTypeAck(String code) {
        return DATA_TYPE_ACK.getOrDefault(code, "未知");
    }

    // 获取唯一识别码
    public static String getUnique(String[] arr) {
        StringBuilder sb = new StringBuilder();
        for (int i = 4; i < 21; i++)
            sb.append((char) hex2int(arr[i]));
        return sb.toString();
    }

    // 获取加密方式
    public static String getEncryptType(String code) {
        return ENCRYPT_TYPE.getOrDefault(code, "未知");
    }

    // 解析数据单元内容（示例：车辆登录、登出、心跳等，后续可扩展）
    public static Map<String, Object> parseDataUnit(String cmdType, String[] data, String startChar) {

        Map<String, Object> map = new HashMap<>();
        switch (cmdType) {
            case "车辆登录":
                map.put(cmdType, parseLogin(data));
                break;
            case "车辆登出":
                map.put(cmdType, parseLogout(data));
                break;
            case "实时信息上报":
                map.put(cmdType, parseRealTime(data, startChar));
                break;
            case "补发信息上报":
                map.put(cmdType, parseReissue(data, startChar));
                break;
            case "DTC数据上报":
                map.put(cmdType, parseDTC(data));
                break;
            case "T-BOX注册":
                map.put(cmdType, parseReg(data));
                break;
            case "升级结果状态上报":
                map.put(cmdType, parseOtaResRep(data));
                break;
            case "ECU升级结果":
                map.put(cmdType, parseEcuOtaResRep(data));
                break;
            case "ECU信息查询":
                map.put(cmdType, parseEcuQuery(data));
                break;
            // 可继续扩展其他命令类型
            default:
                map.put(cmdType, data);
        }
        return map;
    }

    // 车辆登录数据单元解析
    public static Map<String, Object> parseLogin(String[] data) {
        Map<String, Object> map = new HashMap<>();
        if (data.length < 30)
            return map;
        map.put("数据采集时间", getTime(data[0], data[1], data[2], data[3], data[4], data[5]));
        map.put("登录流水号", hex2int(data[6] + data[7]));
        StringBuilder iccid = new StringBuilder();
        for (int i = 8; i < 28; i++)
            iccid.append((char) hex2int(data[i]));
        map.put("ICCID", iccid.toString());
        int sysCount = hex2int(data[28]);
        int sysLen = hex2int(data[29]);
        map.put("可充电储能系统数", sysCount);
        map.put("可充电储能系统编码长度", sysLen);
        StringBuilder sysCode = new StringBuilder();
        for (int i = 30; i < 30 + sysCount * sysLen && i < data.length; i++)
            sysCode.append((char) hex2int(data[i]));
        map.put("可充电储能系统编码", sysCode.toString());
        return map;
    }

    // 车辆登出数据单元解析
    public static Map<String, Object> parseLogout(String[] data) {
        Map<String, Object> map = new HashMap<>();
        if (data.length < 8)
            return map;
        map.put("登出时间", getTime(data[0], data[1], data[2], data[3], data[4], data[5]));
        map.put("登出流水号", hex2int(data[6] + data[7]));
        return map;
    }

    // 实时信息上报数据单元解析（仅示例，详细字段可按需扩展）
    public static Map<String, Object> parseRealTime(String[] data, String startChar) {
        Map<String, Object> map = new HashMap<>();
        if (data.length < 6)
            return map;
        map.put("数据采集时间", getTime(data[0], data[1], data[2], data[3], data[4], data[5]));


        int idx = 6;
        while (idx < data.length) {
            String type = data[idx];
            if(idx +1>= data.length) {
                break;
            }
            switch (type) {
                case "01": // 整车数据
                    Map<String, Object> vehicle = parseVehicle(Arrays.copyOfRange(data, idx, data.length),
                            startChar);
                    map.put("整车数据", vehicle.get("data"));
                    idx = idx + 1 + (Integer) vehicle.get("len");
                    break;
                case "02": // 驱动电机数据
                    Map<String, Object> motors = parseMotors(Arrays.copyOfRange(data, idx, data.length), startChar);
                    map.put("驱动电机数据", motors.get("data"));
                    idx = idx + 1 + (Integer) motors.get("len");
                    break;
                case "03": // 燃料电池数据
                    Map<String, Object> fuel = parseFuelCell(Arrays.copyOfRange(data, idx, data.length));
                    map.put("燃料电池数据", fuel.get("data"));
                    idx = idx + 1 + (Integer) fuel.get("len");
                    break;
                case "04": // 发动机数据
                    Map<String, Object> eng = parseEngine(Arrays.copyOfRange(data, idx, data.length));
                    map.put("发动机数据", eng.get("data"));
                    idx = idx + 1 + (Integer) eng.get("len");
                    break;
                case "05": // 车辆位置数据
                    Map<String, Object> pos = parsePosition(Arrays.copyOfRange(data, idx, data.length), startChar);
                    map.put("车辆位置数据", pos.get("data"));
                    idx = idx + 1 + (Integer) pos.get("len");
                    break;
                case "06":
                    if ("##".equals(startChar)) {
                        // 极值数据
                        Map<String, Object> ext = parseExtremum(Arrays.copyOfRange(data, idx, data.length));
                        map.put("极值数据", ext.get("data"));
                        idx = idx + 1 + (Integer) ext.get("len");
                        break;
                    }
                    if ("$$".equals(startChar)) {
                        // 报警数据
                        Map<String, Object> alarm = parseAlarm(Arrays.copyOfRange(data, idx, data.length),
                                startChar);
                        map.put("报警数据", alarm.get("data"));
                        idx += (Integer) alarm.get("len") + 1;
                        break;
                    }
                case "07":
                    if ("##".equals(startChar)) {
                        // 报警数据
                        Map<String, Object> alarm = parseAlarm(Arrays.copyOfRange(data, idx, data.length),
                                startChar);
                        map.put("报警数据", alarm.get("data"));
                        idx += (Integer) alarm.get("len") + 1;
                        break;
                    }
                    if ("$$".equals(startChar)) {
                        // 动力蓄电池最小并联单元电压数据
                        Map<String, Object> volt = parseBatteryVoltage2025(
                                Arrays.copyOfRange(data, idx, data.length));
                        map.put("动力蓄电池最小并联单元电压数据", volt.get("data"));
                        idx += (Integer) volt.get("len") + 1;
                        break;
                    }
                case "08":
                    if ("##".equals(startChar)) {
                        // 可充电储能装置电压数据
                        Map<String, Object> volt = parseBatteryVoltage(Arrays.copyOfRange(data, idx, data.length));
                        map.put("可充电储能装置电压数据", volt.get("data"));
                        idx += (Integer) volt.get("len") + 1;
                        break;
                    }
                    if ("$$".equals(startChar)) {
                        // 可充电储能装置温度数据
                        Map<String, Object> temp = parseBatteryTemp2025(Arrays.copyOfRange(data, idx, data.length));
                        map.put("动力蓄电池温度数据", temp.get("data"));
                        idx += (Integer) temp.get("len") + 1;
                        break;
                    }
                case "09": // 可充电储能装置温度数据
                    if ("##".equals(startChar)) {
                        Map<String, Object> temp = parseBatteryTemp(Arrays.copyOfRange(data, idx, data.length));
                        map.put("可充电储能装置温度数据", temp.get("data"));
                        idx += (Integer) temp.get("len") + 1;
                        break;
                    }
                    if ("$$".equals(startChar)) {
                        map.put("未知数据", Arrays.copyOfRange(data, idx, data.length));
                        idx = data.length; // 跳出循环
                        break;
                    }
                    // 可扩展：case "96": 新能源车况数据等
                case "30":
                    if ("$$".equals(startChar)) {
                        // 燃料电池电堆数据
                        Map<String, Object> fuelStack = parseFuelCellStack(
                                Arrays.copyOfRange(data, idx, data.length));
                        map.put("燃料电池电堆数据", fuelStack.get("data"));
                        idx += (Integer) fuelStack.get("len") + 1;
                        break;
                    } else{
                        map.put("未知数据", Arrays.copyOfRange(data, idx, data.length));
                        idx = data.length; // 跳出循环
                    }
                case "31":
                    if ("$$".equals(startChar)) {
                        // 超级电容器数据
                        Map<String, Object> superElectricContainer = parseSuperElectricContainer(
                                Arrays.copyOfRange(data, idx, data.length));
                        map.put("超级电容器数据", superElectricContainer.get("data"));
                        idx += (Integer) superElectricContainer.get("len") + 1;
                        break;
                    }  else{
                        map.put("未知数据", Arrays.copyOfRange(data, idx, data.length));
                        idx = data.length; // 跳出循环
                    }
                case "32":
                    if ("$$".equals(startChar)) {
                        // 超级电容器极值数据
                        Map<String, Object> superElectricContainerExtremeValues = parseSuperElectricContainerExtremeValues(
                                Arrays.copyOfRange(data, idx, data.length));
                        map.put("超级电容器极值数据", superElectricContainerExtremeValues.get("data"));
                        idx += (Integer) superElectricContainerExtremeValues.get("len") + 1;
                        break;
                    }  else{
                        map.put("未知数据", Arrays.copyOfRange(data, idx, data.length));
                        idx = data.length; // 跳出循环
                    }
                default:
                    if ("##".equals(startChar)) {
                        map.put("未知数据", Arrays.copyOfRange(data, idx, data.length));
                        idx = data.length; // 跳出循环
                    }
                    if ("$$".equals(startChar)) {
                        map.put("未知数据", Arrays.copyOfRange(data, idx, data.length));
                        idx = data.length; // 跳出循环
                    }
            }
        }
        return map;
    }

    // 燃料电池电堆数据
    public static Map<String, Object> parseFuelCellStack(String[] data) {
        int idx = 0;
        int count = hex2int(data[1]);
        idx = 2;
        Map<String, Object> map = new HashMap<>();
        map.put("燃料电池电堆个数", count);



        List<Map<String, Object>> fuelCellStacks = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            if(idx >= data.length) {
                break;
            }
            Map<String, Object> fuelCellStack = new HashMap<>();
            fuelCellStack.put("燃料电池电堆序号", getValByte(data[idx++], 1, 0));
            fuelCellStack.put("燃料电池电堆电压", getValWord(data[idx++] + data[idx++], 0.1, 0));
            fuelCellStack.put("燃料电池电堆电流", getValWord(data[idx++] + data[idx++], 0.1, 0));
            fuelCellStack.put("氢气入口压力", getValWord(data[idx++] + data[idx++], 0.1, -100));
            fuelCellStack.put("空气入口压力", getValWord(data[idx++] + data[idx++], 0.1, -100));
            fuelCellStack.put("空气入口温度", getValByte(data[idx++], 1, -40));
            // 冷却水出水口温度探针总数
            String coldAirTemperatureCount = getValWord(data[idx++] + data[idx++], 1, 0);
            fuelCellStack.put("冷却水出水口温度探针总数", coldAirTemperatureCount);
            int coldAirTemperatureCount0 = 0;
            try {
                coldAirTemperatureCount0 = Integer.parseInt(coldAirTemperatureCount);
            } catch (Exception e) {
            }

            if(idx >= data.length) {
                break;
            }
            List<String> coldAirTemperatureList = new ArrayList<>();
            for (int j = 0; j < coldAirTemperatureCount0; j++) {
                if(idx >= data.length) {
                    break;
                }
                coldAirTemperatureList.add(getValByte(data[idx++], 1, -40));
            }
            fuelCellStack.put("冷却水出水口温度", coldAirTemperatureList);
            fuelCellStacks.add(fuelCellStack);

        }
        map.put("燃料电池电堆信息表", fuelCellStacks);

        Map<String, Object> result = new HashMap<>();
        result.put("len", idx - 1);
        result.put("data", map);
        return result;
    }

    // 超级电容器数据
    public static Map<String, Object> parseSuperElectricContainer(String[] data) {
        /*
         *
         *
         * | 数据表示内容 | 长度/字节 | 数据类型 | 描述及要求 |
         * |--------------|-----------|----------|------------|
         * | 超级电容器管理系统号 | 1 | BYTE | 有效值范围：1～255，“0xFF”表示无效，“0xFE”表示异常 |
         * | 超级电容器总电压 | 2 | WORD | 有效值范围：0～10 000（表示 0 V～1 000 V），最小计量单元：0.1
         * V，“0xFF”表示无效，“0xFE”表示异常 |
         * | 超级电容器总电流 | 2 | WORD | 有效值范围：0～60 000（数值偏移量 3 000 A，表示 -3 000 A～+3 000
         * A），最小计量单元：0.1 A，“0xFF”表示无效，“0xFE”表示异常 |
         * | 超级电容器单体总数 | 2 | WORD | 有效值范围：1～65 531，“0xFF”表示无效，“0xFE”表示异常 |
         * | 超级电容器单体电压 | 2×M | WORD | 有效值范围：0～60 000（表示 0 V～60.000 V），最小计量单元：0.001
         * V，超级电容器单体电压个数等于单体总数 M，“0xFF”表示无效，“0xFE”表示异常 |
         * | 超级电容器温度探针总数 | 2 | WORD | 有效值范围：1～65 531，“0xFF”表示无效，“0xFE”表示异常 |
         * | 探针温度值 | 1×N | BYTE[N] | 有效值范围：0～250（数值偏移量 40℃，表示
         * -40℃～+210℃），最小计量单元：1℃，“0xFF”表示无效，“0xFE”表示异常 |
         *
         */
        int length = 0;
        Map<String, Object> map = new HashMap<>();

        // 解析超级电容器管理系统号
        if (data.length > length) {
            String value = data[length];
            map.put("超级电容器管理系统号", getValByte(value, 1, 0));
            length++;
        }

        // 解析超级电容器总电压
        if (data.length > length + 1) {
            String voltage = getValWord(data[length] + data[length + 1], 0.1, 0);
            // 有效值范围：0～10 000，最小计量单元：0.1 V
            map.put("超级电容器总电压", voltage);
            length += 2;
        }

        // 解析超级电容器总电流
        if (data.length > length + 1) {
            String current = getValWord(data[length] + data[length + 1], 0.1, -3000);
            // 有效值范围：0～60 000，数值偏移量 3 000 A，表示 -3 000 A～+3 000 A，最小计量单元：0.1 A

            map.put("超级电容器总电流", current);
            length += 2;
        }

        // 解析超级电容器单体总数
        if (data.length > length + 1) {
            String cellCount = getValWord(data[length] + data[length + 1], 1, 0);
            map.put("超级电容器单体总数", cellCount);
            length += 2;
            int cellCount0 = 0;
            try {
                cellCount0 = Integer.parseInt(cellCount);
            } catch (Exception e) {
            }
            // 解析超级电容器单体电压
            if (data.length > length + (cellCount0 * 2) - 1) {
                String[] cellVoltages = new String[cellCount0];
                for (int i = 0; i < cellCount0; i++) {
                    String cellVoltage = getValWord(data[length] + data[length + 1], 0.001, 0);
                    // 有效值范围：0～60 000，表示 0 V～60.000 V，最小计量单元：0.001 V
                    cellVoltages[i] = cellVoltage;
                    length += 2;
                }
                map.put("超级电容器单体电压", cellVoltages);
            }
        }

        // 解析超级电容器温度探针总数
        if (data.length > length + 1) {
            String probeCount = getValWord(data[length] + data[length + 1], 0.001, 0);
            map.put("超级电容器温度探针总数", probeCount);
            length += 2;
            int probeCount0 = 0;
            try {
                probeCount0 = Integer.parseInt(probeCount);
            } catch (Exception e) {
            }
            // 解析探针温度值
            if (data.length > length + probeCount0 - 1) {
                String[] probeTemperatures = new String[probeCount0];
                for (int i = 0; i < probeCount0; i++) {
                    String temperature = getValByte(data[length], 1, -40);
                    // 有效值范围：0～250，数值偏移量 40℃，表示 -40℃～+210℃，最小计量单元：1℃
                    probeTemperatures[i] = temperature;
                    length++;
                }
                map.put("探针温度值", probeTemperatures);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("len", length);
        result.put("data", map);
        return result;
    }

    // 超级电容器极值数据
    public static Map<String, Object> parseSuperElectricContainerExtremeValues(String[] data) {
        int length = 0;
        Map<String, Object> map = new HashMap<>();

        if (data.length > 14) {
            length = 14; // 数据长度
            map.put("超级电容器最高电压电池子系统号", getValByte(data[1], 1, 0));
            map.put("超级电容器最高电压电池单体代号", getValByte(data[2], 1, 0));
            map.put("超级电容器电池单体电压最高值(V)", getValWord(data[3] + data[4], 0.001, 0));
            map.put("超级电容器最低电压电池子系统号", getValByte(data[5], 1, 0));
            map.put("超级电容器最低电压电池单体代号", getValByte(data[6], 1, 0));
            map.put("超级电容器电池单体电压最低值(V)", getValWord(data[7] + data[8], 0.001, 0));
            map.put("超级电容器最高温度子系统号", getValByte(data[9], 1, 0));
            map.put("超级电容器最高温度探针序号", getValByte(data[10], 1, 0));
            map.put("超级电容器最高温度值(℃)", getValByte(data[11], 1, -40));
            map.put("超级电容器最低温度子系统号", getValByte(data[12], 1, 0));
            map.put("超级电容器最低温度探针序号", getValByte(data[13], 1, 0));
            map.put("超级电容器最低温度值(℃)", getValByte(data[14], 1, -40));
        }

        Map<String, Object> result = new HashMap<>();
        result.put("len", length);
        result.put("data", map);
        return result;
    }

    // 整车数据分包解析（完整实现与JS一致）
    public static Map<String, Object> parseVehicle(String[] data, String startChar) {
        Map<String, Object> map = new HashMap<>();
        Integer length = 0;
        Integer max = 20;
        if ("$$".equals(startChar)) {
            max = 18;
        }
        if (data.length > max) {
            length = max;
            map.put("车辆状态", CAR_STATUS.getOrDefault(data[1], "未知"));
            map.put("充电状态", CHARGE_STATUS.getOrDefault(data[2], "未知"));
            map.put("运行模式", RUN_MODE.getOrDefault(data[3], "未知"));
            map.put("车速", getValWord(data[4] + data[5], 0.1, 0));
            map.put("累计里程", getValDword(data[6] + data[7] + data[8] + data[9], 0.1, 0));
            map.put("总电压", getValWord(data[10] + data[11], 0.1, 0));
            map.put("总电流", getValWord(data[12] + data[13], 0.1, -0x3e8));
            map.put("SOC", getValByte(data[14], 1, 0));

            // DCDC状态解析修正（原data[15]改为data[14]）
            map.put("DCDC状态", DCDC_STATUS.getOrDefault(data[15], "未知"));

            // 档位解析修正（统一使用0x0F掩码）
            int gear = hex2int(data[16]);
            map.put("制动", (gear & 0x10) != 0 ? "有" : "无");
            map.put("驱动", (gear & 0x20) != 0 ? "有" : "无");
            int gearNum = gear & 0x0F; // 保持与JS一致的0x0F掩码
            map.put("档位",
                    gearNum == 0 ? "空档"
                            : gearNum < 13 ? gearNum + "档"
                            : gearNum == 13 ? "倒挡" : gearNum == 14 ? "自动D档" : gearNum == 15 ? "停车P档" : "未知");

            map.put("绝缘电阻", getValWord(data[17] + data[18],1,0));
            if ("##".equals(startChar)) {
                map.put("加速踏板行程值",
                        "FE".equals(data[19]) ? "异常" : "FF".equals(data[19]) ? "无效" : hex2int(data[19]) + "%");
                map.put("制动踏板状态",
                        "65".equals(data[20]) ? "有效" : "FF".equals(data[20]) ? "无效" : hex2int(data[20]) + "%");
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("len", length);
        result.put("data", map);
        return result;
    }

    // 驱动电机数据分包解析
    public static Map<String, Object> parseMotors(String[] data, String startChar) {
        Map<String, Object> map = new HashMap<>();

        int count = hex2int(data[1]);
        Integer len = 0;
        Integer max = 12;
        if ("$$".equals(startChar)) {
            max = 10;
        }
        if (data.length > count * max + 1) {
            len = count * max + 1;
        }
        List<Map<String, Object>> motors = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            // 修改基础索引值与JS保持一致
            int base = i * 12 + 2;
            if (base + 12 > data.length)
                break;
            Map<String, Object> m = new HashMap<>();
            // 保持与JS一致的驱动电机序号解析（从索引0开始）
            m.put("驱动电机序号", hex2int(data[base]));
            m.put("驱动电机状态", MOTOR_STATUS.getOrDefault(data[base + 1], data[base + 1]));
            // 保持与JS一致的温度解析（使用十六进制偏移量）
            m.put("驱动电机控制器温度", hex2int(data[base + 2]) - 0x28);
            // 保持与JS一致的转速解析（使用十六进制偏移量）
            m.put("驱动电机转速", hex2int(data[base + 3] + data[base + 4]) - 0x4e20);
            // 保持与JS一致的转矩解析（使用十六进制偏移量）
            if ("##".equals(startChar)) {
                m.put("驱动电机转矩", hex2int(data[base + 5] + data[base + 6]) * 0.1 - 0x7d0);
                m.put("驱动电机温度", hex2int(data[base + 7]) - 0x28);

                m.put("电机控制器输入电压", hex2int(data[base + 8] + data[base + 9]) * 0.1);
                // 保持与JS一致的直流母线电流解析（使用十六进制偏移量）
                // 修改为与JS一致的0x0FA0(4000)
                m.put("电机控制器直流母线电流", hex2int(data[base + 10] + data[base + 11]) * 0.1 - 0x3e8);
            }
            if ("$$".equals(startChar)) {
                if ("FFFFFE".equals(data[base + 5] + data[base + 6] + data[base + 7] + data[base + 8])) {
                    m.put("驱动电机转矩", "异常");
                } else if ("FFFFFF".equals(data[base + 5] + data[base + 6] + data[base + 7] + data[base + 8])) {
                    m.put("驱动电机转矩", "无效");
                } else {
                    m.put("驱动电机转矩",
                            hex2long(data[base + 5] + data[base + 6] + data[base + 7] + data[base + 8]) * 0.1 - 0x7d0);
                }
                m.put("驱动电机温度", hex2int(data[base + 9]) - 0x28);
            }
            motors.add(m);
        }
        map.put("驱动电机个数", count);
        map.put("驱动电机总成信息", motors);

        Map<String, Object> result = new HashMap<>();
        result.put("len", len);
        result.put("data", map);
        return result;
    }

    // 车辆位置数据分包解析
    public static Map<String, Object> parsePosition(String[] data, String startChar) {
        Map<String, Object> map = new HashMap<>();

        Map<String, Object> result = new HashMap<>();

        if ("##".equals(startChar)) {
            int valid = hex2int(data[1]);
            map.put("定位有效性", (valid & 0x1) == 1 ? "无效" : "有效");
            map.put("南北纬", (valid & 0x2) == 0x2 ? "南纬" : "北纬");
            map.put("东西经", (valid & 0x4) == 0x4 ? "西经" : "东经");
            map.put("经度", getValDword(data[2] + data[3] + data[4] + data[5], 0.000001,0));
            map.put("纬度", getValDword(data[6] + data[7] + data[8] + data[9], 0.000001,0));

            result.put("len", 9);
            result.put("data", map);
        }
        if ("$$".equals(startChar)) {
            int valid = hex2int(data[1]);
            map.put("定位状态", (valid & 0x1) == 1 ? "无效" : "有效");
            int zuobiaoxi = hex2int(data[2]);
            switch (zuobiaoxi) {
                case 1:
                    map.put("坐标系", "WGS84坐标系");
                    break;
                case 2:
                    map.put("坐标系", "GCJ02坐标系");
                    break;
                case 3:
                    map.put("坐标系", "其他坐标系");
                    break;
            }

            map.put("经度", getValDword(data[3] + data[4] + data[5] + data[6], 0.000001,0));
            map.put("纬度", getValDword(data[7] + data[8] + data[9] + data[10], 0.000001,0));

            result.put("len", 10);
            result.put("data", map);
        }

        return result;

    }

    // 极值数据分包解析
    public static Map<String, Object> parseExtremum(String[] data) {
        Map<String, Object> map = new HashMap<>();
        Integer length = 14;
        map.put("最高电压电池子系统号", getValByte(data[1], 1, 0));
        map.put("最高电压电池单体代号", getValByte(data[2], 1, 0));
        map.put("电池单体电压最高值", getValWord(data[3] + data[4], 0.001, 0));
        map.put("最低电压电池子系统号", getValByte(data[5], 1, 0));
        map.put("最低电压电池单体代号", getValByte(data[6], 1, 0));
        map.put("电池单体电压最低值", getValWord(data[7] + data[8], 0.001, 0));
        map.put("最高温度子系统号", getValByte(data[9], 1, 0));
        map.put("最高温度探针序号", getValByte(data[10], 1, 0));
        map.put("最高温度值", getValByte(data[11], 1, -40));
        map.put("最低温度子系统号", getValByte(data[12], 1, 0));
        map.put("最低温度探针序号", getValByte(data[13], 1, 0));
        map.put("最低温度", getValByte(data[14], 1, -40));

        Map<String, Object> result = new HashMap<>();
        result.put("len", length);
        result.put("data", map);
        return result;
    }

    // 报警数据分包解析（细化所有字段，按国标和JS实现）
    public static Map<String, Object> parseAlarm(String[] data, String startChar) {

        Map<String, Object> map = new HashMap<>();

        map.put("最高报警等级", ALARM_LEVEL.getOrDefault(data[1], "未知"));
        // 通用报警标志（4字节，32位）
        String alarmFlagHex = data[2] + data[3] + data[4] + data[5];
        long alarmFlag = Long.parseLong(alarmFlagHex, 16);
        Map<String, String> alarmBits = new LinkedHashMap<>();
        alarmBits.put("温度差异", getGeneralAlarmDec(0x0, alarmFlag));
        alarmBits.put("电池高温", getGeneralAlarmDec(0x1, alarmFlag));
        alarmBits.put("车载储能装置类型过压", getGeneralAlarmDec(0x2, alarmFlag));
        alarmBits.put("车载储能装置类型欠压", getGeneralAlarmDec(0x3, alarmFlag));
        alarmBits.put("SOC低", getGeneralAlarmDec(0x4, alarmFlag));
        alarmBits.put("单体电池过压", getGeneralAlarmDec(0x5, alarmFlag));
        alarmBits.put("单体电池欠压", getGeneralAlarmDec(0x6, alarmFlag));
        alarmBits.put("SOC过高", getGeneralAlarmDec(0x7, alarmFlag));
        alarmBits.put("SOC跳变", getGeneralAlarmDec(0x8, alarmFlag));
        alarmBits.put("可充电储能系统不匹配", getGeneralAlarmDec(0x9, alarmFlag));
        alarmBits.put("电池单体一致性差", getGeneralAlarmDec(0xa, alarmFlag));
        alarmBits.put("绝缘", getGeneralAlarmDec(0xb, alarmFlag));
        alarmBits.put("DC-DC温度", getGeneralAlarmDec(0xc, alarmFlag));
        alarmBits.put("制动系统", getGeneralAlarmDec(0xd, alarmFlag));
        alarmBits.put("驱动电机控制器温度", getGeneralAlarmDec(0xe, alarmFlag));
        alarmBits.put("高压互锁状态", getGeneralAlarmDec(0xf, alarmFlag));
        alarmBits.put("驱动电机温度", getGeneralAlarmDec(0x10, alarmFlag));
        alarmBits.put("车载储能装置类型过充", getGeneralAlarmDec(0x11, alarmFlag));
        // ...如有更多位可继续补充...
        map.put("通用报警标志", alarmBits);
        int idx = 6;
        String energyFaultCount = getValByte(data[idx++], 1, 0);
        map.put("可充电储能装置故障总数", energyFaultCount);
        Integer energyFaultCount0 = 0;
        try {
            energyFaultCount0 = Integer.parseInt(energyFaultCount);
        } catch (Exception e) {
        }
        List<String> energyFaultList = new ArrayList<>();
        if (idx >= data.length) {
            Map<String, Object> result = new HashMap<>();
            result.put("len", idx - 1);
            result.put("data", map);
            return result;
        }
        // 修改为与JS一致的故障码读取方式
        for (int i = 0; i < energyFaultCount0 && idx + 4 < data.length && i < 0xff; i++) {
            energyFaultList.add(data[idx++] + data[idx++] + data[idx++] + data[idx++]);
        }
        map.put("可充电储能装置故障码列表", energyFaultList);
        String driveMotorFaultCount = getValByte(data[idx++], 1, 0);
        Integer driveMotorFaultCount0 = 0;
        try {
            driveMotorFaultCount0 = Integer.parseInt(driveMotorFaultCount);
        } catch (Exception e) {
        }
        map.put("驱动电机故障总数", driveMotorFaultCount);
        List<String> driveMotorFaultList = new ArrayList<>();
        // 修改为与JS一致的故障码读取方式
        for (int i = 0; i < driveMotorFaultCount0 && idx + 4 < data.length && i < 0xff; i++) {
            driveMotorFaultList.add(data[idx++] + data[idx++] + data[idx++] + data[idx++]);
        }
        map.put("驱动电机故障码列表", driveMotorFaultList);
        if (idx >= data.length) {
            Map<String, Object> result = new HashMap<>();
            result.put("len", idx - 1);
            result.put("data", map);
            return result;
        }
        String engineFaultCount = getValByte(data[idx++], 1, 0);
        map.put("发动机故障总数", engineFaultCount);
        Integer engineFaultCount0 = 0;
        try {
            engineFaultCount0 = Integer.parseInt(engineFaultCount);
        } catch (Exception e) {
        }

        if (idx >= data.length) {
            Map<String, Object> result = new HashMap<>();
            result.put("len", idx - 1);
            result.put("data", map);
            return result;
        }
        if (idx >= data.length) {
            Map<String, Object> result = new HashMap<>();
            result.put("len", idx - 1);
            result.put("data", map);
            return result;
        }
        List<String> engineFaultList = new ArrayList<>();
        // 修改为与JS一致的故障码读取方式
        for (int i = 0; i < engineFaultCount0 && idx < data.length && i < 0xff; i++) {
            engineFaultList.add(data[idx++] + data[idx++] + data[idx++] + data[idx++]);
        }
        map.put("发动机故障码列表", engineFaultList);
        if (idx >= data.length) {
            Map<String, Object> result = new HashMap<>();
            result.put("len", idx - 1);
            result.put("data", map);
            return result;
        }
        String otherFaultCount = getValByte(data[idx++], 1, 0);
        map.put("其他故障总数", otherFaultCount);

        if (idx >= data.length) {
            Map<String, Object> result = new HashMap<>();
            result.put("len", idx - 1);
            result.put("data", map);
            return result;
        }
        List<String> otherFaultList = new ArrayList<>();
        Integer otherFaultCount0 = 0;
        try {
            otherFaultCount0 = Integer.parseInt(otherFaultCount);
        } catch (Exception e) {
        }

        if (idx >= data.length) {
            Map<String, Object> result = new HashMap<>();
            result.put("len", idx - 1);
            result.put("data", map);
            return result;
        }
        // 修改为与JS一致的故障码读取方式
        for (int i = 0; i < otherFaultCount0 * 0x4 && idx < data.length && i < 0xff; i++) {
            otherFaultList.add(data[idx++] + data[idx++] + data[idx++] + data[idx++]);
        }
        map.put("其他故障码列表", otherFaultList);

        if (idx >= data.length) {
            Map<String, Object> result = new HashMap<>();
            result.put("len", idx - 1);
            result.put("data", map);
            return result;
        }
        // 2025年新增
        if ("$$".equals(startChar)) {
            // 通用报警故障总数
            String commonFaultCount = getValByte(data[idx++], 1, 0);

            if (idx >= data.length) {
                Map<String, Object> result = new HashMap<>();
                result.put("len", idx - 1);
                result.put("data", map);
                return result;
            }
            // 通用报警故障等级列表
            List<String> commonFaultList = new ArrayList<>();
            map.put("通用报警故障总数", commonFaultCount);
            Integer commonFaultCount0 = 0;
            try {
                commonFaultCount0 = Integer.parseInt(commonFaultCount);
            } catch (Exception e) {
            }
            for (int i = 0; i < commonFaultCount0 * 0x2 && idx < data.length && i < 0xff; i++) {
                commonFaultList.add(data[idx++] + data[idx++]);
            }
            map.put("通用报警故障等级列表", commonFaultList);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("len", idx - 1);
        result.put("data", map);
        return result;
    }

    // 补发信息上报数据单元解析（结构与实时信息类似）
    public static Map<String, Object> parseReissue(String[] data, String startChar) {
        return parseRealTime(data, startChar);
    }

    // 可充电储能装置电压数据分包解析（示例实现，按国标结构）
    public static Map<String, Object> parseBatteryVoltage(String[] data) {
        Map<String, Object> map = new HashMap<>();
        if (data == null || data.length < 2)
            return map;

        // 可充电储能子系统个数
        String subCount = getValByte(data[1], 1, 0);
        Integer subCount0 = 0;
        try {
            subCount0 = Integer.parseInt(subCount);
        } catch (Exception e) {
        }
        List<Map<String, Object>> subs = new ArrayList<>();
        int idx = 2; // 修改起始索引与JS保持一致

        for (int i = 0; i < subCount0; i++) {
            if (idx + 5 > data.length)
                break;
            Map<String, Object> sub = new HashMap<>();
            // 子系统号
            sub.put("可充电储能子系统号", getValByte(data[idx++], 1, 0));
            // 可充电储能装置电压（修改为与JS一致的计算方式）
            sub.put("可充电储能装置电压", getValWord(data[idx++] + data[idx++], 0.1, 0));
            // 可充电储能装置电流（修改为与JS一致的偏移量）
            sub.put("可充电储能装置电流", getValWord(data[idx++] + data[idx++], 0.1, -0x3e8));
            // 单体电池总数
            sub.put("单体电池总数", getValWord(data[idx++] + data[idx++], 1, 0));
            // 本帧起始电池序号
            sub.put("本帧起始电池序号", getValWord(data[idx++] + data[idx++], 1, 0));
            // 本帧单体电池总数
            String cellCount = getValByte(data[idx++], 1, 0);
            sub.put("本帧单体电池总数", cellCount);

            List<Map<String, String>> cells = new ArrayList<>();
            Integer cellCount0 = 0;
            try {
                cellCount0 = Integer.parseInt(cellCount);
            } catch (Exception e) {
            }
            for (int j = 0; j < cellCount0 && idx + 1 < data.length; j++) {
                // 单体电池电压（修改为与JS一致的计算方式）
                Map<String, String> cell = new HashMap<>();
                cell.put(String.valueOf(j + 1), getValWord(data[idx++] + data[idx++], 0.001, 0));
                cells.add(cell);
            }
            sub.put("单体电池电压列表", cells);
            subs.add(sub);
        }

        map.put("可充电储能子系统个数", subCount);
        map.put("可充电储能子系统电压信息列表", subs);

        Map<String, Object> result = new HashMap<>();
        result.put("len", idx - 1);
        result.put("data", map);
        return result;
    }

    // 动力蓄电池最小并联单元电压数据解析（示例实现，按国标结构）
    public static Map<String, Object> parseBatteryVoltage2025(String[] data) {
        Map<String, Object> map = new HashMap<>();

        // 可充电储能子系统个数
        String subCount = getValByte(data[1], 1, 0);
        Integer subCount0 = 0;
        try {
            subCount0 = Integer.parseInt(subCount);
        } catch (Exception e) {
        }
        List<Map<String, Object>> subs = new ArrayList<>();
        int idx = 2; // 修改起始索引与JS保持一致

        for (int i = 0; i < subCount0; i++) {
            if (idx + 5 > data.length)
                break;
            Map<String, Object> sub = new HashMap<>();
            // 子系统号
            sub.put("动力蓄电池包号", getValByte(data[idx++], 1, 0));
            // 可充电储能装置电压（修改为与JS一致的计算方式）
            sub.put("动力蓄电池包电压", getValWord(data[idx++] + data[idx++], 0.1, 0));
            // 可充电储能装置电流（修改为与JS一致的偏移量）
            sub.put("动力蓄电池包电流", getValWord(data[idx++] + data[idx++], 0.1, -0x3e8));
            // 单体电池总数
            sub.put("最小并联单元总数", getValWord(data[idx++] + data[idx++], 1, 0));
            // 最小并联单元总数
            int cellCount = 0;
            try {
                cellCount = Integer.parseInt((String) sub.get("最小并联单元总数"));
            } catch (Exception e) {
            }
            List<Map<String, String>> cells = new ArrayList<>();
            for (int j = 0; j < cellCount && idx + 1 < data.length; j++) {
                // 单体电池电压（修改为与JS一致的计算方式）
                Map<String, String> cell = new HashMap<>();
                cell.put(String.valueOf(j + 1), getValWord(data[idx++] + data[idx++], 0.001, 0));
                cells.add(cell);
            }
            sub.put("本帧最小并联单元电压", cells);
            subs.add(sub);
        }

        map.put("动力蓄电池包个数", subCount);
        map.put("动力蓄电池最小并联单元电压信息列表", subs);

        Map<String, Object> result = new HashMap<>();
        result.put("len", idx - 1);
        result.put("data", map);
        return result;
    }

    // 可充电储能装置温度数据分包解析（示例实现）
    public static Map<String, Object> parseBatteryTemp(String[] data) {
        Map<String, Object> map = new HashMap<>();
        int subCount = 0;
        if (!"FE".equals(data[1]) && !"FF".equals(data[1])) {
            subCount = hex2int(data[1]);
        }
        List<Map<String, Object>> subs = new ArrayList<>();
        int idx = 2;
        for (int i = 0; i < subCount; i++) {
            Map<String, Object> sub = new HashMap<>();
            sub.put("可充电储能子系统号", getValByte(data[idx], 1, 0));
            idx++;
            String tempCount = getValWord(data[idx] + data[idx + 1], 1, 0);
            idx += 2;
            sub.put("可充电储能温度探针个数", tempCount);
            int tempCount0 = 0;
            try {
                tempCount0 = Integer.parseInt(tempCount);
            } catch (Exception e) {
            }
            List<String> temps = new ArrayList<>();
            for (int j = 0; j < tempCount0; j++) {
                if (idx >= data.length)
                    break;
                temps.add(getValByte(data[idx++], 1, -40));
            }
            sub.put("单体温度", temps);
            subs.add(sub);
        }
        map.put("可充电储能子系统数", subCount);
        map.put("可充电储能子系统各温度探针检测到的温度值", subs);
        Map<String, Object> result = new HashMap<>();
        result.put("len", idx - 1);
        result.put("data", map);
        return result;
    }

    public static Map<String, Object> parseBatteryTemp2025(String[] data) {
        Map<String, Object> map = new HashMap<>();
        int subCount = 0;
        if (!"FE".equals(data[1]) && !"FF".equals(data[1])) {
            subCount = hex2int(data[1]);
        }
        List<Map<String, Object>> subs = new ArrayList<>();
        int idx = 2;
        for (int i = 0; i < subCount; i++) {
            if (idx >= data.length){
                break;
            }
            Map<String, Object> sub = new HashMap<>();
            sub.put("动力蓄电池包号", getValByte(data[idx], 1, 0));
            idx++;
            String tempCount = getValWord(data[idx] + data[idx + 1], 1, 0);
            idx += 2;
            sub.put("动力蓄电池包温度探针个数", tempCount);
            List<String> temps = new ArrayList<>();
            int tempCount0 = 0;
            try {
                tempCount0 = Integer.parseInt(tempCount);
            } catch (Exception e) {
            }
            for (int j = 0; j < tempCount0; j++) {
                if (idx >= data.length)
                    break;
                temps.add(getValByte(data[idx++], 1, -40));
            }
            sub.put("各温度探针检测到的温度值", temps);
            subs.add(sub);
        }
        map.put("动力蓄电池包个数", subCount);
        map.put("动力蓄电池温度信息列表", subs);
        Map<String, Object> result = new HashMap<>();
        result.put("len", idx - 1);
        result.put("data", map);
        return result;
    }

    // 发动机数据分包解析（示例实现）
    public static Map<String, Object> parseEngine(String[] data) {
        Map<String, Object> map = new HashMap<>();
        map.put("发动机状态", ENGINE_STATUS.getOrDefault(data[1], data[1]));
        map.put("曲轴转速", getValWord(data[2] + data[3], 1, 0));
        map.put("燃料消耗率", getValWord(data[4] + data[5], 0.01, 0));
        Map<String, Object> result = new HashMap<>();
        result.put("len", 5);
        result.put("data", map);
        return result;
    }

    // 燃料电池数据分包解析（示例实现）
    public static Map<String, Object> parseFuelCell(String[] data) {
        Map<String, Object> map = new HashMap<>();
        if (data.length < 18)
            return map;

        map.put("燃料电池电压", getValWord(data[0] + data[1], 0.1, 0));
        map.put("燃料电池电流", getValWord(data[2] + data[3], 0.1, 0));
        map.put("燃料消耗率", getValWord(data[4] + data[5], 0.01, 0));

        String tempProbeCount = getValWord(data[6] + data[7], 1, 0);
        map.put("燃料电池温度探针总数", tempProbeCount);
        int tempProbeCount0 = 0;
        try {
            tempProbeCount0 = Integer.parseInt(tempProbeCount);
        } catch (Exception e) {
        }
        List<String> tempProbeValues = new ArrayList<>();
        for (int i = 0; i < tempProbeCount0; i++) {
            if (8 + i < data.length) {
                tempProbeValues.add(getValByte(data[8 + i], 1, 0));
            }
        }
        map.put("燃料电池温度探针值", tempProbeValues);

        int offset = 8 + tempProbeCount0;
        if (offset + 4 <= data.length) {
            map.put("氢系统中最高温度", getValWord(data[offset] + data[offset + 1], 0.1, -40));
            map.put("氢系统中最高温度探针代号", getValByte(data[offset + 2], 1, 0));
            map.put("氢气最高浓度", getValWord(data[offset + 3] + data[offset + 4], 0.01, 0));
        }

        // 更新offset位置
        offset += 5;
        if (offset + 2 <= data.length) {
            map.put("氢气最高浓度传感器代号", getValByte(data[offset], 1, 0));
            map.put("氢气最高压力", getValWord(data[offset + 1] + data[offset + 2], 0.1, 0));
        }

        // 更新offset位置
        offset += 3;
        if (offset + 1 <= data.length) {
            map.put("氢气最高压力传感器代号", getValByte(data[offset], 1, 0));

            // DCDC状态
            String dcdcStatus = "未知";
            if (offset + 1 < data.length) {
                switch (data[offset + 1]) {
                    case "01":
                        dcdcStatus = "工作";
                        break;
                    case "02":
                        dcdcStatus = "断开";
                        break;
                    case "FE":
                        dcdcStatus = "异常";
                        break;
                    case "FF":
                        dcdcStatus = "无效";
                        break;
                }
            }
            map.put("高压DCDC状态", dcdcStatus);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("len", offset + 1);
        result.put("data", map);
        return result;
    }

    public static Integer hex2integerE(String hexStr) {
        try {
            return Integer.parseInt(hexStr);
        } catch (Exception e) {
            return 0;
        }
    }

    // DTC数据分包解析（故障码）
    public static Map<String, Object> parseDTC(String[] data) {
        Map<String, Object> map = new HashMap<>();
        if (data.length < 7)
            return map;
        map.put("数据采集时间", getTime(data[0], data[1], data[2], data[3], data[4], data[5]));
        String ecuCount = getValByte(data[6], 1, 0);
        List<Map<String, Object>> ecuList = new ArrayList<>();
        int idx = 7;
        for (int i = 0; i < hex2integerE(ecuCount); i++) {
            if (idx + 3 > data.length)
                break;
            Map<String, Object> ecu = new HashMap<>();
            ecu.put("ECU编码", getValByte(data[idx++], 1, 0));
            String dtcCount = getValWord(data[idx++] + data[idx++], 1, 0);
            List<String> dtcs = new ArrayList<>();
            for (int j = 0; j < hex2integerE(dtcCount); j++) {
                if (idx + 3 >= data.length)
                    break;
                String dtc = data[idx++] + data[idx++] + data[idx++] + data[idx++];
                dtcs.add(dtc);
            }
            ecu.put("DTC信息", dtcs);
            ecuList.add(ecu);
        }
        map.put("ECU数目", ecuCount);
        map.put("ECU列表", ecuList);
        return map;
    }

    // T-BOX注册数据单元解析
    public static Map<String, Object> parseReg(String[] data) {
        Map<String, Object> map = new HashMap<>();
        if (data.length < 30)
            return map;
        map.put("数据采集时间", getTime(data[0], data[1], data[2], data[3], data[4], data[5]));
        map.put("TBOX编号长度", getValByte(data[6], 1, 0));
        String tboxLen = getValByte(data[6], 1, 0);
        Integer tboxLen0 = hex2integerE(tboxLen);
        StringBuilder tbox = new StringBuilder();
        for (int i = 7; i < 7 + tboxLen0 && i < data.length; i++) {
            tbox.append(getValByte(data[i], 1, 0));
        }
        map.put("TBOX编号", tbox.toString());

        map.put("ICCID长度", 20);
        StringBuilder iccid = new StringBuilder();
        for (int i = 7 + tboxLen0; i < 7 + tboxLen0 + 20 && i < data.length; i++) {
            iccid.append(getValByte(data[i], 1, 0));
        }
        map.put("ICCID", iccid.toString());

        map.put("IMEI长度", getValByte(data[7 + tboxLen0 + 20], 1, 0));
        String imeiLen = getValByte(data[7 + tboxLen0 + 20], 1, 0);
        Integer imeiLen0 = hex2integerE(imeiLen);
        StringBuilder imei = new StringBuilder();
        for (int i = 8 + tboxLen0 + 20; i < 8 + tboxLen0 + 20 + imeiLen0 && i < data.length; i++) {
            imei.append(getValByte(data[i], 1, 0));
        }
        map.put("IMEI", imei.toString());

        map.put("自定义固件版本长度", getValByte(data[8 + tboxLen0 + 20 + imeiLen0], 1, 0));
        String fwLen = getValByte(data[8 + tboxLen0 + 20 + imeiLen0], 1, 0);
        Integer fwLen0 = hex2integerE(fwLen);
        StringBuilder firmware = new StringBuilder();
        for (int i = 9 + tboxLen0 + 20 + imeiLen0; i < 9 + tboxLen0 + 20 + imeiLen0 + fwLen0 && i < data.length; i++) {
            firmware.append(getValByte(data[i], 1, 0));
        }
        map.put("固件版本号", firmware.toString());

        map.put("自定义硬件版本长度", getValByte(data[9 + tboxLen0 + 20 + imeiLen0 + fwLen0], 1, 0));
        String hwLen = getValByte(data[9 + tboxLen0 + 20 + imeiLen0 + fwLen0], 1, 0);
        Integer hwLen0 = hex2integerE(hwLen);
        StringBuilder hardware = new StringBuilder();
        for (int i = 10 + tboxLen0 + 20 + imeiLen0 + fwLen0; i < 10 + tboxLen0 + 20 + imeiLen0 + fwLen0 + hwLen0
                && i < data.length; i++) {
            hardware.append(getValByte(data[i], 1, 0));
        }
        map.put("硬件版本号", hardware.toString());

        return map;
    }

    // 升级结果状态上报数据单元解析
    public static Map<String, Object> parseOtaResRep(String[] data) {
        Map<String, Object> map = new HashMap<>();
        if (data.length < 10)
            return map;
        map.put("时间", getTime(data[0], data[1], data[2], data[3], data[4], data[5]));
        map.put("升级类型", "启动升级".equals(OTA_TYPE.getOrDefault(data[6], "未知")) ? "启动升级" : "升级结果");
        map.put("应答标志", "成功".equals(OTA_STATUS.getOrDefault(data[7], "未知")) ? "成功" : "失败");
        map.put("自定义固件版本长度", getValByte(data[8], 1, 0));
        String fwLen = getValByte(data[8], 1, 0);
        Integer fwLen0 = hex2integerE(fwLen);
        StringBuilder firmware = new StringBuilder();
        for (int i = 9; i < 9 + fwLen0 && i < data.length; i++) {
            firmware.append(getValByte(data[i], 1, 0));
        }
        map.put("固件版本号", firmware.toString());

        map.put("自定义硬件版本长度", getValByte(data[9 + fwLen0], 1, 0));
        String hwLen = getValByte(data[9 + fwLen0], 1, 0);
        Integer hwLen0 = hex2integerE(hwLen);
        StringBuilder hardware = new StringBuilder();
        for (int i = 10 + fwLen0; i < 10 + fwLen0 + hwLen0 && i < data.length; i++) {
            hardware.append(getValByte(data[i], 1, 0));
        }
        map.put("硬件版本号", hardware.toString());

        map.put("升级失败错误码", "0x" + data[10 + fwLen0 + hwLen0]);
        if ("0xFE".equals(data[10 + fwLen0 + hwLen0])) {
            map.put("扩展错误码", "0x" + data[11 + fwLen0 + hwLen0] + ",0x" + data[12 + fwLen0 + hwLen0]);
        }

        return map;
    }

    // ECU升级结果数据单元解析
    public static Map<String, Object> parseEcuOtaResRep(String[] data) {
        Map<String, Object> map = new HashMap<>();
        if (data.length < 15)
            return map;
        map.put("时间", getTime(data[0], data[1], data[2], data[3], data[4], data[5]));
        map.put("ECUID", getValByte(data[6], 1, 0));
        map.put("升级结果", "成功".equals(OTA_RESULT.getOrDefault(data[7], "未知")) ? "成功" : "失败");

        map.put("自定义固件版本长度", getValByte(data[8], 1, 0));
        String fwLen = getValByte(data[8], 1, 0);
        Integer fwLen0 = hex2integerE(fwLen);
        StringBuilder firmware = new StringBuilder();
        for (int i = 9; i < 9 + fwLen0 && i < data.length; i++) {
            firmware.append(getValByte(data[i], 1, 0));
        }
        map.put("固件版本号", firmware.toString());

        map.put("自定义硬件版本长度", getValByte(data[9 + fwLen0], 1, 0));
        String hwLen = getValByte(data[9 + fwLen0], 1, 0);
        Integer hwLen0 = hex2integerE(hwLen);
        StringBuilder hardware = new StringBuilder();
        for (int i = 10 + fwLen0; i < 10 + fwLen0 + hwLen0 && i < data.length; i++) {
            hardware.append(getValByte(data[i], 1, 0));
        }
        map.put("硬件版本号", hardware.toString());

        map.put("升级失败错误码", "0x" + data[10 + fwLen0 + hwLen0]);
        if ("0xFE".equals(data[10 + fwLen0 + hwLen0])) {
            map.put("扩展错误码", "0x" + data[11 + fwLen0 + hwLen0] + ",0x" + data[12 + fwLen0 + hwLen0]);
        }

        map.put("供应商代码", data[12 + fwLen0 + hwLen0] + data[13 + fwLen0 + hwLen0] + data[14 + fwLen0 + hwLen0]);

        return map;
    }

    // ECU信息查询数据单元解析
    public static Map<String, Object> parseEcuQuery(String[] data) {
        Map<String, Object> map = new HashMap<>();
        if (data.length < 8)
            return map;
        map.put("数据采集时间", getTime(data[0], data[1], data[2], data[3], data[4], data[5]));
        map.put("ECU数目", getValByte(data[6], 1, 0));

        String paramCount = getValByte(data[7], 1, 0);
        Integer paramCount0 = hex2integerE(paramCount);
        map.put("参数总数", paramCount);

        List<String> params = new ArrayList<>();
        for (int i = 8; i < 8 + paramCount0 && i < data.length; i++) {
            params.add(data[i]);
        }
        map.put("参数ID列表", params);

        return map;
    }

    // 辅助：字节数组转int（支持负偏移）
    public static String getValByte(String hex, int scale, int offset) {
        if ("FE".equals(hex))
            return "异常"; // 异常
        if ("FF".equals(hex))
            return "无效"; // 无效
        return String.valueOf(hex2int(hex) * scale + offset);
    }

    public static String getValWord(String hex, double scale, int offset) {
        if ("FFFE".equals(hex))
            return "异常";
        if ("FFFF".equals(hex))
            return "无效";
        if(scale>=1)
            return String.valueOf((int) (hex2int(hex) * scale + offset));
        else
            return String.valueOf((float) (hex2int(hex) * scale + offset));
    }

    public static String getValDword(String hex, double scale, int offset) {
        if ("FFFFFFFE".equals(hex))
            return "异常";
        if ("FFFFFFFF".equals(hex))
            return "无效";
        if(scale>=1)
            return String.valueOf((long) (hex2long(hex) * scale + offset));
        else
            return String.valueOf((float) (hex2long(hex) * scale + offset));
    }

    // 辅助：格式化16进制字符串（去空格，每两位加空格）
    // 已有formatHex

    // 辅助：十六进制字符串转int（已实现hex2int）

    // 其他辅助方法可继续补充...

    // 例：通用报警标志解析（仅示意，具体可按JS实现细化）
    public static String getGeneralAlarmDec(int bit, long alarmFlag) {
        return (alarmFlag & (1L << bit)) != 0 ? "报警" : "正常";
    }

}

